#include "kernel_operator.h"
#include "math.h"

constexpr int32_t TOTAL_LENGTH = 2048;
constexpr int32_t USE_CORE_NUM = 8;
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;
constexpr int32_t TILE_NUM = 8;
constexpr int32_t BUFFER_NUM = 2;
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM;

/*
  NOTE on complex number representation:
  complex64 = pair<float32,float32> = {float32(real),float32(imag)}
*/

template<typename TYPE_X,typename TYPE_Y, typename TYPE_Z,bool IsExistBigCore> 
class KernelComplexMul {
public:
    __aicore__ inline KernelComplexMul() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint64_t smallCoreDataNum,
                                uint64_t bigCoreDataNum, uint64_t bigCoreLoopNum, 
                                uint64_t smallCoreLoopNum, uint64_t ubPartDataNum, 
                                uint64_t smallCoreTailDataNum, uint64_t bigCoreTailDataNum, 
                                uint64_t tailBlockNum) 
    {
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint64_t coreNum = AscendC::GetBlockIdx();
        uint64_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->ubPartDataNum = ubPartDataNum;
        if constexpr (IsExistBigCore) 
        {
          if (coreNum < tailBlockNum) 
          { 
            this->coreDataNum = bigCoreDataNum;
            this->tileNum = bigCoreLoopNum;
            this->tailDataNum = bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = smallCoreDataNum;
            this->tileNum = smallCoreLoopNum;
            this->tailDataNum = smallCoreTailDataNum;
            globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = smallCoreLoopNum;
          this->tailDataNum = smallCoreTailDataNum;
          globalBufferIndex = smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ TYPE_Y*)y + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ TYPE_Z*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Y));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Z));

        pipe.InitBuffer(abuf , this->ubPartDataNum * sizeof(float)*2);
        pipe.InitBuffer(bbuf , this->ubPartDataNum * sizeof(float)*2);
  
        pipe.InitBuffer(indexbuf , this->ubPartDataNum * sizeof(uint32_t)*2);
        index = indexbuf.Get<uint32_t>(this->ubPartDataNum*2);
        pipe.InitBuffer(revindexbuf , this->ubPartDataNum * sizeof(uint32_t)*2);
        revindex = revindexbuf.Get<uint32_t>(this->ubPartDataNum*2);

        /*
        AscendC::CreateVecIndex(index , (unsigned)0, this->ubPartDataNum);
        AscendC::CreateVecIndex(index[this->ubPartDataNum],  (unsigned)0, this->ubPartDataNum);
        AscendC::Muls(index, index, (uint32_t)8, this->ubPartDataNum); // 0,8,16,24,... + 0,8,16,24,...
        AscendC::Adds(index[this->ubPartDataNum], index[this->ubPartDataNum], (uint32_t)4, this->ubPartDataNum);

        As Cann does not supprt this API, we use SetValue to set index and revindex
      */
        //0,8,16,24,... real
        //4,12,20,28,... imag

        // 1) real,imag,real,imag ... -> real,real ...+  imag,imag ...
        //-> 0,8,16,24,...,4,12,20,28,...

        // 2) real,real ... + imag,imag ... -> real,imag,real,imag ...
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;

        if( loopCount-1 > 0)//save time for tail only case
          for(int i=0;i<this->processDataNum;i++){
            index.SetValue(i, i*8),
            index.SetValue(i+this->processDataNum, i*8+4);
            revindex.SetValue(2*i, i*4),
            revindex.SetValue(2*i+1, (i+this->processDataNum)*4);
          }

        for (int32_t i = 0; i < (loopCount-1); i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;

        for(int i=0;i<this->processDataNum;i++){
            index.SetValue(i, i*8),
            index.SetValue(i+this->processDataNum, i*8+4);
            revindex.SetValue(2*i, i*4),
            revindex.SetValue(2*i+1, (i+this->processDataNum)*4);
       }

        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
      AscendC::DataCopy(xLocal, xGm[progress * this->ubPartDataNum], this->processDataNum);
      inQueueX.EnQue(xLocal);

      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.AllocTensor<TYPE_Y>();
      AscendC::DataCopy(yLocal, yGm[progress * this->ubPartDataNum], this->processDataNum);
      inQueueY.EnQue(yLocal);
    }

    __aicore__ inline void Compute(int32_t progress)//sin(pi x)/(pi*x)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.DeQue<TYPE_Y>();
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.AllocTensor<TYPE_Z>();
    
      AscendC::LocalTensor<float> a = abuf.Get<float>();
      AscendC::LocalTensor<float> b = bbuf.Get<float>();


      auto xf=xLocal.template ReinterpretCast<float>();
      auto yf=yLocal.template ReinterpretCast<float>();
      auto zf=zLocal.template ReinterpretCast<float>();


     AscendC::Gather(a, xf, index, (uint32_t)0, 2* this->processDataNum); 
     //a [x1 x1 ... y1 y1 ...]

     AscendC::Gather(b, yf, index, (uint32_t)0, 2* this->processDataNum); 
     //b [x2 x2 ... y2 y2 ...]
    
     AscendC::Mul(xf, a, b, 2*this->processDataNum); 
     // c [x1*x2 x1*x2 ... y1*y2 y1*y2 ...]
     
     AscendC::Mul(yf,a,b[this->processDataNum],this->processDataNum); 
     //d(front) [x1*y2 x1*y2 ...]
     AscendC::Mul(yf[this->processDataNum],a[this->processDataNum],b,this->processDataNum); 
     //d(back) [y1*x2 y1*x2 ...]

     //d [x1*y2 x1*y2 ...  y1*x2 y1*x2 ...]

      //complemul (x1+iy1)*(x2+iy2) = (x1*x2-y1*y2) + i(x1*y2+y1*x2)
      AscendC::Sub(a, xf, xf[this->processDataNum], this->processDataNum); // ac-bd
      AscendC::Add(a[this->processDataNum], yf, yf[this->processDataNum], this->processDataNum); // ad+bc

      //reshuffle
      AscendC::Gather(zf, a, revindex, (uint32_t)0, 2*this->processDataNum); // output index;

      outQueueZ.EnQue<TYPE_Z>(zLocal);
      inQueueX.FreeTensor(xLocal);
      inQueueY.FreeTensor(yLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.DeQue<TYPE_Z>();  
      AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
      outQueueZ.FreeTensor(zLocal);
    }
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX,inQueueY;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> abuf, bbuf, indexbuf,revindexbuf;

    AscendC::LocalTensor<uint32_t> index,revindex;

    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Y> yGm;
    AscendC::GlobalTensor<TYPE_Z> zGm;
    uint64_t coreDataNum;
    uint64_t tileNum;
    uint64_t ubPartDataNum;
    uint64_t tailDataNum;
    uint64_t processDataNum;
};

extern "C" __global__ __aicore__ void complex_mul_custom(GM_ADDR x,GM_ADDR y,GM_ADDR z)
{
    // GET_TILING_DATA(tiling_data, tiling);
    KernelComplexMul<uint64_t, uint64_t, uint64_t, 0 >op;
    int blockLength = TOTAL_LENGTH;
    int bufsz=64;

    op.Init(x, y, z,
            blockLength, blockLength, 
            blockLength/bufsz,blockLength/bufsz,
            bufsz,
            bufsz,bufsz,blockLength/bufsz+1);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void complex_mul_custom_do(uint32_t blockDim, void *stream, std::pair<float,float> *x, std::pair<float,float> *y,std::pair<float,float> *z)
{
    complex_mul_custom<<<blockDim, nullptr, stream>>>(x, y, z);
}
#endif
